<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsySalesOrderDouyinTable;
use App\Http\Models\Mysql\SsySalesOrderTopTable;
use App\Http\Repository\OmsRepository;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use PhpOffice\PhpSpreadsheet\IOFactory;

class importData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:importData {--key=} {--id=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '本地文件导入数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $key = $this->option("key") ?? "";
        $id = $this->option("id") ?? "";
        if(empty($key)){
            die("请输入key");
        }
        switch ($key){
            case "SALES_EXCEL_IMPORT":
                $this->importSales();
                break;
        }
    }

    public function importSales()
    {
        $processKey = "SALES_EXCEL_IMPORT";
        //获取正在导出的任务进度
        $cache = Cache::get($processKey) ?: [];
        if(empty($cache)){
            dd("无导入任务");
        }
        $sourceClass = $cache['param']['source'] ?? "top";
        $file = storage_path("cache/sales/").$cache['file'];
        $spreadsheet = IOFactory::load($file);
        $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
        array_shift($sheetData);
        $total = count($sheetData);
        $createTime = date('Y-m-d H:i:s');
        $combineSkuMap = [];
        foreach ($sheetData as $index => $item){
            $orderDate = date('Y-m-d', strtotime($item['A']));
            $orderNumber = trim($item['B']);
            $num = (Int)(trim($item['D']));
            $index++;
            $jyItem = (new SsyJyProductListTable())->where('product_code', $item['C'])->exists();
            $skus = [$item['C']];
            $combineSku = "";
            if(!$jyItem){
                $combineSku = $item['C'];
                $skus = $combineSkuMap[$combineSku] ?? [];
                if(empty($skus)){
                    $res = OmsRepository::searchCombineItem(1, 20, $combineSku);
                    $details = $res['data'][0]['details'] ?? [];
                    $skus = array_column($details, 'skuCode');
                    $combineSkuMap[$combineSku] = $skus;
                }
            }
            foreach ($skus as $sku) {
                $data = [
                    'order_date' => $orderDate,
                    'order_number' => $orderNumber,
                    'sku' => $sku,
                    'type_no' => preg_replace("/(^[A-Z]+[0-9]+)(.*)/is", '$1', $sku),
                    'combine_sku' => $combineSku,
                    'num' => $num,
                    'createtime' => $createTime
                ];
                switch ($sourceClass){
                    case "top":
                        $exist = (new SsySalesOrderTopTable())->where('order_date', $orderDate)->where('sku', $sku)->where('order_number', $orderNumber)->first();
                        if(!empty($exist)){
                            unset($data['createtime']);
                            (new SsySalesOrderTopTable())->updateData($exist->id, $data);
                        }else{
                            (new SsySalesOrderTopTable())->createData($data);
                        }
                        break;
                    case "douyin":
                        $exist = (new SsySalesOrderDouyinTable())->where('order_date', $orderDate)->where('sku', $sku)->where('order_number', $orderNumber)->first();
                        if(!empty($exist)){
                            unset($data['createtime']);
                            (new SsySalesOrderDouyinTable())->updateData($exist->id, $data);
                        }else{
                            (new SsySalesOrderDouyinTable())->createData($data);
                        }
                        break;
                }
            }
            //计算当前下载进度
            $process = round($index/$total*100, 2);
            $cache['process'] = $process >= 100 ? 99.99 : $process;
            Cache::put($processKey, $cache, (new Carbon())->now()->addSeconds(60));
        }
        Cache::forget($processKey);
        dd("数据写入完成！！！");
    }
}
